package com.sso.shiro;

import com.alibaba.fastjson.JSONObject;
import com.sso.common.ConstantDate;
import com.sso.common.enums.FlagStatus;
import com.sso.common.enums.SysResourceEnum;
import com.sso.entity.SysResource;
import com.sso.manager.SysResourceManager;
import com.tools.util.JSONUtils;
import com.tools.util.StrUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Admin on 2016/3/7.
 */
public abstract class MyAuthorizationFilter extends AuthorizationFilter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysResourceManager resourceManager;
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return this.isUrlStatus(request,response)&& (isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue));
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest httpRequest=(HttpServletRequest)request;
        HttpServletResponse httpResponse=(HttpServletResponse)response;
        Subject subject = getSubject(request, response);
        String type=httpRequest.getHeader("X-Requested-With");
        //ajax
        if("XMLHttpRequest".equals(type)){
            if(subject.getPrincipal()==null){
                JSONUtils.outputJson(FlagStatus.ERROR.value,"您未登陆或已登陆超时请重新登陆",httpResponse);
            }else{
                JSONUtils.outputJson(FlagStatus.ERROR.value,"您没有权限访问，如有疑问请咨询管理人员",httpResponse);
            }
        }else{
            if(subject.getPrincipal()==null){
                saveRequestAndRedirectToLogin(request, response);
            }else{
                String unauthorizedUrl = getUnauthorizedUrl();
                if (StringUtils.hasText(unauthorizedUrl)) {
                    WebUtils.issueRedirect(request, response, unauthorizedUrl);
                } else {
                    WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            }
        }
        return false;
    }

    /**
     * 返回错误信息地址是否正确
     * @param request
     * @return
     */
    protected boolean isUrlStatus(ServletRequest request,ServletResponse response){
        boolean flag=true;
        try {
            HttpServletRequest httpRequest = WebUtils.toHttp(request);
            HttpServletResponse httpResponse = WebUtils.toHttp(response);
            String url = httpRequest.getServletPath();
            SysResource resource = resourceManager.selectByURL(url);
            if(StrUtils.isEmpty(resource.getId())){
                return true;
            }
            String type=httpRequest.getHeader("X-Requested-With");
            String msg = isUrlAccessStatus(httpRequest);
            if(StrUtils.isNotEmpty(msg)){
                if("XMLHttpRequest".equals(type)){
                    JSONUtils.outputJson(FlagStatus.ERROR.value,msg,httpResponse);
                    flag=false;
                }else {
                    if(SysResourceEnum.status.DEL.key.equals(resource.getStatus())){
                        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_NOT_FOUND);
                        flag=false;
                    }else if(SysResourceEnum.status.STOP.key.equals(resource.getStatus())){
                        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN);
                        flag=false;
                    }else{

                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 校验URL是否有校
     * @param request
     * @return
     */
    protected String isUrlAccessStatus(HttpServletRequest request){
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String url = httpRequest.getServletPath();
        SysResource resource = resourceManager.selectByURL(url);
        if(StrUtils.isEmpty(resource.getId())){
            return "";
        }
        if(SysResourceEnum.status.DEL.key.equals(resource.getStatus())){
            return "很抱歉，您要访问的地址不存在！";
        }else if(SysResourceEnum.status.STOP.key.equals(resource.getStatus())){
            return "很抱歉，您访问的地址已经暂停访问，如有问题请联系管理人员";
        }else{
            return "";
        }
    }
}
